import 'package:flutter/material.dart';
import 'package:jd_shop/base/Constant.dart';
import 'package:jd_shop/utils/Utils.dart';
import 'package:jd_shop/widget/BaseLoadind.dart';
import 'package:jd_shop/widget/CartNum.dart';
import 'package:provider/provider.dart';

import '../../event/ProductContentEvent.dart';
import '../../model/QueryShoppingCartBean.dart';
import '../../net/ShoppingOrderService.dart';
import '../../provider/CartProvider.dart';
import '../../routers/AppRoutes.dart';
import '../../services/ScreenAdaper.dart';
import '../../utils/Storage.dart';
import '../../utils/ToastMsg.dart';

class CartPage extends StatefulWidget {
  const CartPage({super.key});

  @override
  State<StatefulWidget> createState() {
    return _CartPageState();
  }
}

class _CartPageState extends State<CartPage> {
  bool isLoading = true;
  List<QueryShoppingCartBean> cartList = [];
  bool isSetting = false;

  @override
  void initState() {
    super.initState();
    queryShoppingCartList();
    eventBus.on<UserLoginEvent>().listen((event) {
      queryShoppingCartList();
    });
  }

  void deleteGoods(pragma) {
    ShoppingOrderService.deleteCartGoodsNet(pragma).then((value) {
      queryShoppingCartList();
    });
  }

  void queryShoppingCartList() {
    ShoppingOrderService.queryShoppingCartList(callback: (res) {})
        .then((onValue) {
      isLoading = false;
      cartList = onValue!;
      setState(() {});
    });
  }

  Widget _ItemShop(QueryShoppingCartBean cart) {
    return Container(
      child: Column(children: [
        Container(
          width: double.infinity,
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(
              ScreenAdapter.width(10),
            ),
          ),
          margin: EdgeInsets.only(
              top: ScreenAdapter.height(10),
              left: ScreenAdapter.width(15),
              right: ScreenAdapter.height(10)),
          padding: EdgeInsets.all(ScreenAdapter.width(10)),
          child: Column(
            children: [
              Row(children: [
                isSetting
                    ? InkWell(
                        child: Icon(
                            cart.isSelect
                                ? Icons.check_box
                                : Icons.check_box_outline_blank,
                            color: Colors.blue),
                        onTap: () {
                          selectAllShopGoods(cart, !cart.isSelect);
                          sumMoney();
                        },
                      )
                    : const Text(""),
                SizedBox(width: ScreenAdapter.width(5)),
                Text(cart.shopName.toString())
              ]),
              SizedBox(height: ScreenAdapter.height(10)),
              ListView(
                  shrinkWrap: true,
                  physics: const NeverScrollableScrollPhysics(),
                  children: cart.goodsDetailsList!.map((goods) {
                    return Container(
                      margin: EdgeInsets.only(bottom: ScreenAdapter.height(10)),
                      child: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            isSetting
                                ? InkWell(
                                    child: Icon(
                                        goods.isSelect
                                            ? Icons.check_box
                                            : Icons.check_box_outline_blank,
                                        color: Colors.blue),
                                    onTap: () {
                                      goods.isSelect = !goods.isSelect;
                                      upDataCartList();
                                    },
                                  )
                                : const Text(""),
                            SizedBox(width: ScreenAdapter.width(10)),
                            InkWell(
                              child: SizedBox(
                                width: ScreenAdapter.width(80),
                                height: ScreenAdapter.height(80),
                                child: ClipRRect(
                                  borderRadius: BorderRadius.circular(
                                      ScreenAdapter.width(5)),
                                  child: Image.network(
                                      goods.goodsImage.toString(),
                                      fit: BoxFit.cover),
                                ),
                              ),
                              onTap: () {
                                Navigator.pushNamed(
                                    context, AppRoutes.GOODS_DETAIL,
                                    arguments: {
                                      "goodsId": goods.goodsId,
                                      "commonId": goods.commonId,
                                    });
                              },
                            ),
                            SizedBox(width: ScreenAdapter.width(10)),
                            SizedBox(
                              height: ScreenAdapter.height(80),
                              width: ScreenAdapter.getScreenWidth() -
                                  ScreenAdapter.width(170),
                              child: Column(
                                crossAxisAlignment: CrossAxisAlignment.start,
                                mainAxisAlignment:
                                    MainAxisAlignment.spaceBetween,
                                children: [
                                  Text(
                                    goods.goodsName.toString(),
                                    maxLines: 2,
                                    style: TextStyle(
                                        color: Colors.black,
                                        fontSize: ScreenAdapter.fontSize(12),
                                        overflow: TextOverflow.ellipsis),
                                  ),
                                  Row(
                                    mainAxisAlignment: MainAxisAlignment.center,
                                    children: [
                                      Text(
                                        "￥${Utils.formatDouble(goods.goodsPrice)}",
                                        style: TextStyle(
                                            color: Colors.red,
                                            fontSize:
                                                ScreenAdapter.fontSize(12)),
                                      ),
                                      const Expanded(
                                        flex: 1,
                                        child: Text(""),
                                      ),
                                      CartNum(
                                          max: goods.goodsMaxSale,
                                          countNum: goods.goodsNum,
                                          onChangedRemove: (value) {
                                            goods.goodsNum = value;
                                          },
                                          onChangedAdd: (value) {
                                            goods.goodsNum = value;
                                          })
                                    ],
                                  ),
                                ],
                              ),
                            ),
                          ]),
                    );
                  }).toList()),
            ],
          ),
        )
      ]),
    );
  }

  Future<void> _onRefresh() async {
    queryShoppingCartList();
  }

  late CartProvider watch;

  void selectAllGoods(bool isSelect) {
    cartList.forEach((item) {
      item.isSelect = isSelect;
      item.goodsDetailsList?.forEach((goods) {
        goods.isSelect = isSelect;
      });
    });
    setState(() {});
  }

  void selectAllShopGoods(QueryShoppingCartBean shop, bool isSelect) {
    shop.goodsDetailsList?.forEach((goods) {
      goods.isSelect = isSelect;
    });
    shop.isSelect = isSelect;
    upDataCartList();
  }

  void upDataCartList() {
    bool isSelectAll = true;
    cartList.forEach((item) {
      bool isSelectShop = true;
      item.goodsDetailsList?.forEach((goods) {
        if (!goods.isSelect) {
          isSelectShop = false;
        }
      });
      item.isSelect = isSelectShop;
      if (!isSelectShop) {
        isSelectAll = false;
      }
    });
    watch.isSelectAll = isSelectAll;
    sumMoney();
  }

  void sumMoney() {
    double sumMoney = 0.0;
    cartList.forEach((item) {
      item.goodsDetailsList?.forEach((goods) {
        if (goods.isSelect) {
          sumMoney = (goods.goodsPrice * goods.goodsNum) + sumMoney;
        }
      });
    });
    watch.setSumMoney(sumMoney);
  }

  @override
  Widget build(BuildContext context) {
    watch = context.watch<CartProvider>();
    ScreenAdapter.init(context);
    return RefreshIndicator(
        onRefresh: _onRefresh,
        child: Container(
          color: Colors.grey.shade200,
          alignment: Alignment.center,
          child: Column(children: [
            Container(
              color: Colors.blue,
              width: double.infinity,
              height:
                  ScreenAdapter.height(40) + ScreenAdapter.getStatusBarHeight(),
              padding: EdgeInsets.only(top: ScreenAdapter.getStatusBarHeight()),
              child: Stack(
                children: [
                  Align(
                    alignment: Alignment.centerRight,
                    child: Container(
                      width: ScreenAdapter.width(50),
                      height: double.infinity,
                      alignment: Alignment.center,
                      child: InkWell(
                        child: const Text(
                          "管理",
                          style: TextStyle(color: Colors.white),
                        ),
                        onTap: () {
                          setState(() {
                            isSetting = !isSetting;
                          });
                        },
                      ),
                    ),
                  ),
                  Align(
                    child: InkWell(
                      child: Text(
                        "购物车",
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: ScreenAdapter.fontSize(16)),
                      ),
                      onTap: () {
                        Storage.setString(SpKeys.USER_TOKEN,
                            "3235d238-6509-4995-af11-1ecf441d3641");
                        ToastMsg.show("写入成功!");
                      },
                    ),
                  ),
                  // Positioned(
                  //   top: 0,
                  //   right: 0,
                  //   left: 0,
                  //   bottom: 0,
                  //   child: Text(
                  //     watch.content,
                  //     style: TextStyle(color: Colors.white, fontSize: ScreenAdapter.fontSize(16)),
                  //   ),
                  // ),
                ],
              ),
            ),
            Expanded(
                flex: 1,
                child: BaseLoadind(
                    isLoading: isLoading,
                    child: MediaQuery.removePadding(
                      context: context,
                      removeTop: true,
                      child: ListView.builder(
                          itemCount: cartList.length,
                          itemBuilder: (context, index) {
                            return _ItemShop(cartList[index]);
                          }),
                    ))),
            Container(
              padding: EdgeInsets.only(
                  left: ScreenAdapter.width(15),
                  right: ScreenAdapter.width(15)),
              color: Colors.blue,
              height: ScreenAdapter.height(40),
              child: Row(children: [
                isSetting
                    ? InkWell(
                        child: Icon(
                            watch.isSelectAll
                                ? Icons.check_box
                                : Icons.check_box_outline_blank,
                            color: Colors.white),
                        onTap: () {
                          watch.isSelectAll = !watch.isSelectAll;
                          selectAllGoods(watch.isSelectAll);
                          sumMoney();
                          setState(() {});
                        },
                      )
                    : Text(""),
                SizedBox(width: ScreenAdapter.width(5)),
                Text(
                  "全选",
                  style: TextStyle(
                      color: Colors.white,
                      fontSize: ScreenAdapter.fontSize(10)),
                ),
                const Expanded(
                  flex: 1,
                  child: Text(""),
                ),
                !isSetting
                    ? Text(
                        "合计：￥${Utils.formatDouble(watch.sumMoney)}",
                        textAlign: TextAlign.right,
                        style: TextStyle(
                            color: Colors.white,
                            fontSize: ScreenAdapter.fontSize(10)),
                      )
                    : const Text(""),
                SizedBox(width: ScreenAdapter.width(10)),
                !isSetting
                    ? InkWell(
                        child: Container(
                          width: ScreenAdapter.width(40),
                          height: ScreenAdapter.height(25),
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: Colors.white,
                              borderRadius: BorderRadius.circular(
                                  ScreenAdapter.width(5))),
                          child: Text(
                            "结算",
                            style: TextStyle(
                                color: Colors.blue,
                                fontSize: ScreenAdapter.fontSize(10)),
                          ),
                        ),
                        onTap: () {
                          ToastMsg.show("结算");
                          Navigator.pushNamed(context, AppRoutes.PAY,
                              arguments: {});
                        },
                      )
                    : const Text(""),
                isSetting
                    ? InkWell(
                        child: Container(
                            width: ScreenAdapter.width(40),
                            height: ScreenAdapter.height(25),
                            alignment: Alignment.center,
                            decoration: BoxDecoration(
                                color: Colors.white,
                                borderRadius: BorderRadius.circular(
                                    ScreenAdapter.width(5))),
                            child: Text(
                              "删除",
                              style: TextStyle(
                                  color: Colors.blue,
                                  fontSize: ScreenAdapter.fontSize(10)),
                            )),
                        onTap: () {
                          List<String> goodsList = [];
                          cartList.forEach((item) {
                            item.goodsDetailsList?.forEach((goods) {
                              if (goods.isSelect) {
                                goodsList.add(goods.goodsId.toString());
                              }
                            });
                          });
                          deleteGoods(goodsList);
                        })
                    : const Text("")
              ]),
            )
          ]),
        ));
  }
}
